#include"tcpsocket.hpp"
#include"select.hpp"

int main()
{
    TcpSocket srv_sock;
    srv_sock.createServer(9000);
    Select s;
    s.Add(srv_sock);
    while(1){
        std::vector<TcpSocket> arry;
        bool ret = s.Wait(arry);
        if(ret == false){
            return -1;
        }
        for(auto &sock:arry){
            //就绪的套接字是监听套接字，则accept
            //就绪的套接字是通信套接字，则Recv
            if(sock.FD() == srv_sock.FD()){
                TcpSocket cli_sock;
                bool ret = srv_sock.Accept(cli_sock);
                if(ret == false)continue;
                s.Add(cli_sock);//将新建套接字也添加可读监控
            }else{
                std::string buf;
                ret = sock.Recv(buf);
                if(ret == false){
                    s.Del(sock);
                    sock.Close();
                    continue;
                }
                std::cout<<"client say; "<<buf<<std::endl;
                buf.clear();
                std::cout<<"server say: ";
                fflush(stdout);
                std::cin>>buf;
                ret = sock.Send(buf);
                if(ret == false){
                    s.Del(sock);
                    sock.Close();
                    continue;
                }
            }
        }
        
    }
    srv_sock.Close();
    return 0;
}